package cn.rengy.dsstaticdemo.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import cn.rengy.dsstaticdemo.yzm.ValidateCodeFilter;




/**
 * spring security配置
 * 
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
	@Autowired private ValidateCodeFilter validateCodeFilter;
	
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	
	@Override
	public void configure(WebSecurity web) throws Exception {
		//忽略 Spring Security 对静态资源的控制
		web.ignoring().antMatchers("/**/*.css","/**/*.svg","/**/*.png","/**/*.jpg","/**/*.html");
	}
	
	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception{
		httpSecurity.formLogin() //表单提交 
		.loginPage("/index") //自定义登录页面 
		.loginProcessingUrl("/user/login") //登录访问路径，必须和表单提交接口一样
		.defaultSuccessUrl("/admin",true) //认证成功之后跳转的路径 
		.and().authorizeRequests() //设置哪些路径可以直接访问，不需要认证 
		.antMatchers("/user/login","/index","/code/image").permitAll()
		.anyRequest().authenticated() //需要认证
		//.and().sessionManagement().invalidSessionUrl("/")//seesion失效后的跳转路径
		.and().headers().frameOptions().sameOrigin()
		.and().csrf().disable() //关闭csrf防护
		
		;
		httpSecurity.addFilterBefore(
	            validateCodeFilter, UsernamePasswordAuthenticationFilter.class); // 添加验证码校验过滤器
	}

	    
}
